/* eslint-disable array-callback-return */
import React from 'react';
import { connect } from 'dva';
import router from 'umi/router';
import { Form } from '@ant-design/compatible';
import '@ant-design/compatible/assets/index.css';
import { Button, message, Spin, Collapse, Modal } from 'antd';
import { ExclamationCircleOutlined } from '@ant-design/icons';
import FooterToolbar from '@/components/FooterToolbar';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';
import BasicInfo from './Add/BasicInfo';
import InvoiceInfo from './Add/InvoiceInfo';
import MailingAddress from './Add/MailingAddress';
import BankInfo from './Add/BankInfo';
import Contacts from './Add/Contacts';
import CostCenter from './Add/CostCenter';

const { Panel } = Collapse;
// 组合新增的数据：发票，地址，联系人,成本中心
const getInvoiceArrayData = (data, fileList) => {
  const indexList = [];
  Object.keys(data).forEach(key => {
    if (key.indexOf('list_') > -1) {
      const index = parseInt(key.charAt(key.length - 1), 10);
      if (indexList.indexOf(index) === -1) {
        indexList.push(index);
      }
    }
  });
  return indexList.map(i => ({
    vatCoprName: data[`vatCoprName_list_${i}`],
    invType: data[`invType_list_${i}`].key,
    taxerIdNo: data[`taxerIdNo_list_${i}`],
    bankOfDepoName: data[`bankOfDepoName_list_${i}`] || '',
    bankAcco: data[`bankAcco_list_${i}`] || '',
    invPhone: data[`invPhone_list_${i}`] || '',
    invAddr: data[`invAddr_list_${i}`] || '',
    remark: data[`remark_list_${i}`] || '',
    invoiceAffixList: fileList[`list_${i}`] || [],
  }));
};

const getContactsArrayData = data => {
  const indexList = [];
  Object.keys(data).forEach(key => {
    if (key.indexOf('list_') > -1) {
      const index = parseInt(key.charAt(key.length - 1), 10);
      if (indexList.indexOf(index) === -1) {
        indexList.push(index);
      }
    }
  });

  return indexList.map(i => ({
    name: data[`name_list_${i}`],
    gender: data[`gender_list_${i}`] ? data[`gender_list_${i}`].key : '',
    position: data[`position_list_${i}`],
    phoneNo: data[`phoneNo_list_${i}`],
    tel: data[`tel_list_${i}`] || '',
    qq: data[`qq_list_${i}`] || '',
    wx: data[`wx_list_${i}`] || '',
    email: data[`email_list_${i}`] || '',
    addr: data[`addr_list_${i}`] || '',
    birthDay: data[`birthDay_list_${i}`] ? data[`birthDay_list_${i}`].format('YYYY-MM-DD') : '',
    hasChild: data[`hasChild_list_${i}`] ? data[`hasChild_list_${i}`].key : '',
    remark: data[`remark_list_${i}`] || '',
  }));
};

const getCostArrayData = data => {
  const indexList = [];
  Object.keys(data).forEach(key => {
    if (key.indexOf('list_') > -1) {
      const index = parseInt(key.charAt(key.length - 1), 10);
      if (indexList.indexOf(index) === -1) {
        indexList.push(index);
      }
    }
  });
  return indexList.map(i => ({
    name: data[`list_${i}`],
  }));
};

const getAddressArrayData = data => {
  const indexList = [];
  Object.keys(data).forEach(key => {
    if (key.indexOf('list_') > -1) {
      const index = parseInt(key.charAt(key.length - 1), 10);
      if (indexList.indexOf(index) === -1) {
        indexList.push(index);
      }
    }
  });

  return indexList.map(i => ({
    contPerName: data[`contPerName_list_${i}`],
    contPerPhone: data[`contPerPhone_list_${i}`],
    mailArea: data[`mailAreaName_list_${i}`],
    mailCounty: data[`mailArea_list_${i}`][data[`mailArea_list_${i}`].length - 1],
    mailAddr: data[`mailAddr_list_${i}`],
    remark: data[`remark_list_${i}`] || '',
  }));
};

@connect(({ customer, loading, publicdata, addemp, login }) => ({
  pageData: customer.pageData,
  loading: loading.models.custedit || loading.effects['customer/submit'] || false,
  expandForm: customer.expandForm,
  activeKey: customer.activeKey,
  formFieldsValue: customer.formFieldsValue,
  dictCode: publicdata.dictCode,
  addemp,
  suppReplaceCorpId: customer.suppReplaceCorpId,
  login,
  isRequired: customer.isRequired,
  supplyList: customer.supplyList,
}))
@Form.create()
class BasicForm extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      comTypeList: [],
      industryCodeList: [],
      idTypeList: [],
      taxerTypeList: [],
      genderList: [],
      hasChildList: [],
      activeKeyList: [],
      custAffixList: [],
      invoiceAffixList: {},
      invTypeList: [],
      custNames: '',
      custNamestwo: '',
      primId: '',
      company: true, // 是否是本公司
    };
    this.ref = {};
  }

  componentDidMount() {
    const { dispatch, login } = this.props;
    dispatch({
      type: 'publicdata/fetchDictCode',
      payload: [
        'CUST_TAB',
        'CORP_NATURE',
        'INDST_CODE',
        'CUST_ID_TYPE',
        'TAXPAYER_TYPE',
        'BANK_ID',
        'GENDER',
        'HAS_CHILD',
        'MINI_INV_TYPE',
      ],
    }).then(dictCode => {
      if (dictCode) {
        const sortNumber = (a, b) => a.itemCode - b.itemCode;
        dictCode.CUST_TAB.sort(sortNumber);
        this.setState({
          comTypeList: dictCode.CORP_NATURE,
          industryCodeList: dictCode.INDST_CODE,
          idTypeList: dictCode.CUST_ID_TYPE,
          taxerTypeList: dictCode.TAXPAYER_TYPE,
          bankList: dictCode.BANK_ID,
          genderList: dictCode.GENDER,
          hasChildList: dictCode.HAS_CHILD,
          invTypeList: dictCode.MINI_INV_TYPE,
        });
      }
    });
    // 获取供应商名称列表数据
    dispatch({
      type: 'customer/getPlatOrAutoSupp',
      payload: {
        name: null,
      },
    });

    // 获取当前角色所在公司对应的平台供应商
    dispatch({
      type: 'customer/plasuppList',
      payload: {},
    }).then(res => {
      if (res.success && res.data) {
        if (login.baseUser && login.baseUser.suppId) {
          if (login.baseUser.suppId === res.data[0].suppId) {
            dispatch({
              type: 'customer/updateModelData',
              payload: { isRequired: true },
            });
          }
        }
        dispatch({
          type: 'customer/updateModelData',
          payload: { suppReplaceCorpId: res.data[0].suppId },
        });
      }
    });
  }

  // 切换折叠面板
  changePanel = key => {
    this.setState({ activeKeyList: key });
  };

  // 获取客户信息文件参数
  getFileInfo = custAffixList => {
    this.setState({ custAffixList });
  };

  getCustName = name => {
    this.setState({ custNames: name });
  };

  getCustNametwo = uniCreditCode => {
    // console.log(name)
    this.setState({ custNamestwo: uniCreditCode });
  };

  // 获取增值税发票文件
  getAffixList = invoiceAffixList => {
    this.setState({ invoiceAffixList });
  };

  // 获取所属客服
  getCustPrim = obj => {
    this.setState({ primId: obj.key });
  };

  // 取消
  cancel = () => {
    const { dispatch } = this.props;
    dispatch({
      type: 'customer/updateModelData',
      payload: {
        formFieldsValue: {},
        expandForm: false,
        pageData: {
          pagination: {
            current: 1,
            pageSize: 10,
            total: 10,
          },
        },
      },
    });
    router.push('/salemanage/customer/index');
  };

  // 提交数据
  sumSubmit = e => {
    e.preventDefault();
    const {
      activeKeyList,
      custAffixList,
      invoiceAffixList,
      custNames,
      custNamestwo,
      primId,
      company,
    } = this.state;
    const { dispatch } = this.props;
    let custInfo = {};
    let isSubmit = true;
    let submitData = {};
    let invoiceList = []; // 发票信息      //
    let mailAddrList = []; // 邮寄地址   //
    let custBankAccount = null; // 银行账户信息
    const mdCustId = null;
    let custContactsList = []; // 联系人信息      //
    let custCostCenterList = []; // 成本中心    //
    activeKeyList.forEach(key => {
      this.ref[key].validateFieldsAndScroll((err, values) => {
        if (!err) {
          switch (key) {
            case 'invoiceInfo':
              Object.keys(invoiceAffixList).forEach(keys => {
                if (invoiceAffixList[keys].length) {
                  invoiceAffixList[keys].map(f => {
                    const temp = f;
                    delete temp.uid;
                  });
                }
              });
              invoiceList = getInvoiceArrayData(values, invoiceAffixList);
              break;
            case 'mailingAddressInfo':
              mailAddrList = getAddressArrayData(values);
              break;
            case 'bankInfo':
              Object.keys(values).forEach(keys => {
                const temp = values;
                if (values[keys] && values[keys].key) {
                  temp[keys] = values[keys].key;
                } else {
                  temp[keys] = values[keys] ? values[keys] : '';
                }
              });
              custBankAccount = values;
              break;
            case 'contactsInfo':
              custContactsList = getContactsArrayData(values);
              break;
            case 'costCenterInfo':
              custCostCenterList = getCostArrayData(values);
              break;
            default:
              break;
          }
        } else {
          isSubmit = false;
        }
      });
    });
    this.ref.basicInfo.validateFieldsAndScroll((err, values) => {
      const obj = values;
      console.log(values,'this.props.fmNcNo');
      delete obj.custAffixList;
      if (!err) {
        custInfo = values;
        custInfo.name = custNames;

        custInfo.uniCreditCode = custNamestwo;
        // 所属客服
        custInfo.primId = primId;
        Object.keys(values).forEach(key => {
          if (values[key] && values[key].key) {
            custInfo[key] = values[key].key;
          } else {
            custInfo[key] = values[key] ? values[key] : null;
          }
        });
        if (custAffixList.length) {
          custAffixList.map(f => {
            const ff = f;
            delete ff.uid;
          });
        }
        submitData = {
          ...custInfo,
          custAffixList,
          invoiceList,
          mailAddrList,
          custBankAccount,
          custContactsList,
          custCostCenterList,
          mdCustId,
        };
      } else {
        isSubmit = false;
      }
    });
    if (isSubmit) {
      if(custInfo.fmNcNo!==null){
        dispatch({
          type: 'customer/checkSubmit',
          payload: submitData,
        }).then(response => {
          if (response.success) {
            if (response.data && response.data.message) {
              Modal.confirm({
                title: '请注意！',
                content: `${response.data.message}`,
                okText: '继续提交',
                cancelText: '返回修改',
                icon: <ExclamationCircleOutlined />,
                onOk: () => {
                  dispatch({
                    type: 'customer/submit',
                    payload: submitData,
                  }).then(res => {
                    if (res.success) {
                      this.setState({ custAffixList: [], invoiceAffixList: [] });
                      dispatch({
                        type: 'customer/updateModelData',
                        payload: {
                          formFieldsValue: {},
                          expandForm: false,
                          pageData: {
                            pagination: {
                              current: 1,
                              pageSize: 10,
                              total: 10,
                            },
                          },
                        },
                      });
                      if (!company) {
                        message.success('客户创建成功，已默认关联供应商合同');
                      }  else {
                        message.success('新增成功');
                      }
                      router.push('/salemanage/customer/index');
                    } else {
                      message.warning(`${res.message || '新增失败！'}`);
                    }
                  });
                },
              });
            } else {
              dispatch({
                type: 'customer/submit',
                payload: submitData,
              }).then(res => {
                if (res.success) {
                  this.setState({ custAffixList: [], invoiceAffixList: [] });
                  dispatch({
                    type: 'customer/updateModelData',
                    payload: {
                      formFieldsValue: {},
                      expandForm: false,
                      pageData: {
                        pagination: {
                          current: 1,
                          pageSize: 10,
                          total: 10,
                        },
                      },
                    },
                  });
                  if (!company) {
                    message.success('客户创建成功，已默认关联供应商合同');
                  }  else {
                    message.success('新增成功');
                  }
                  router.push('/salemanage/customer/index');
                } else {
                  message.warning(`${res.message || '新增失败！'}`);
                }
              });
            }
          } else {
            message.warning(`${response.message || '新增检验失败！'}`);
          }
        });
      }else{
        dispatch({
          type: 'customer/submit',
          payload: submitData,
        }).then(res => {
          if (res.success) {
            this.setState({ custAffixList: [], invoiceAffixList: [] });
            dispatch({
              type: 'customer/updateModelData',
              payload: {
                formFieldsValue: {},
                expandForm: false,
                pageData: {
                  pagination: {
                    current: 1,
                    pageSize: 10,
                    total: 10,
                  },
                },
              },
            });
            if (!company) {
              message.success('客户创建成功，已默认关联供应商合同');
            }  else {
              message.success('新增成功');
            }
            router.push('/salemanage/customer/index');
          } else {
            message.warning(`${res.message || '新增失败！'}`);
          }
        });
      }
    }
  };

  // 是不是本公司
  isCompany = e => {
    const { suppReplaceCorpId, dispatch } = this.props;
    if (e === suppReplaceCorpId) {
      this.setState({
        company: true,
      });
      dispatch({
        type: 'customer/updateModelData',
        payload: {
          isRequired: true,
        },
      });
    } else {
      this.setState({
        company: false,
      });
      dispatch({
        type: 'customer/updateModelData',
        payload: {
          isRequired: false,
        },
      });
    }
  };

  render() {
    const {
      comTypeList,
      industryCodeList,
      idTypeList,
      taxerTypeList,
      genderList,
      hasChildList,
      bankList,
      invTypeList,
      activeKeyList,
      company,
    } = this.state;
    const { loading, suppReplaceCorpId, isRequired, supplyList } = this.props;
    return (
      <PageHeaderWrapper>
        <Spin tip="Loading..." spinning={loading}>
          <BasicInfo
            ref={ref => {
              this.ref.basicInfo = ref;
            }}
            comTypeList={comTypeList}
            industryCodeList={industryCodeList}
            idTypeList={idTypeList}
            supplyList={supplyList}
            suppReplaceCorpId={suppReplaceCorpId}
            getFileInfo={fileInfo => this.getFileInfo(fileInfo)}
            getCustName={name => this.getCustName(name)}
            getCustNametwo={uniCreditCode => this.getCustNametwo(uniCreditCode)}
            getCustPrim={value => this.getCustPrim(value)}
            isCompany={e => this.isCompany(e)}
            isRequired={isRequired}
          />
          {company ? (
            <Collapse
              style={{ marginBottom: 24 }}
              activeKey={activeKeyList}
              onChange={this.changePanel}
            >
              <Panel
                header={<span style={{ fontWeight: 'bolder', fontSize: 16 }}>发票信息</span>}
                key="invoiceInfo"
              >
                <InvoiceInfo
                  ref={ref => {
                    this.ref.invoiceInfo = ref;
                  }}
                  taxerTypeList={taxerTypeList}
                  invTypeList={invTypeList}
                  getAffixList={fileInfo => this.getAffixList(fileInfo)}
                />
              </Panel>
              <Panel
                header={<span style={{ fontWeight: 'bolder', fontSize: 16 }}>邮寄地址信息</span>}
                key="mailingAddressInfo"
              >
                <MailingAddress
                  ref={ref => {
                    this.ref.mailingAddressInfo = ref;
                  }}
                />
              </Panel>
              <Panel
                header={<span style={{ fontWeight: 'bolder', fontSize: 16 }}>银行账户信息</span>}
                key="bankInfo"
              >
                <BankInfo
                  ref={ref => {
                    this.ref.bankInfo = ref;
                  }}
                  bankList={bankList}
                />
              </Panel>
              <Panel
                header={<span style={{ fontWeight: 'bolder', fontSize: 16 }}>联系人信息</span>}
                key="contactsInfo"
              >
                <Contacts
                  genderList={genderList}
                  hasChildList={hasChildList}
                  ref={ref => {
                    this.ref.contactsInfo = ref;
                  }}
                />
              </Panel>
              <Panel
                header={<span style={{ fontWeight: 'bolder', fontSize: 16 }}>成本中心信息</span>}
                key="costCenterInfo"
              >
                <CostCenter
                  ref={ref => {
                    this.ref.costCenterInfo = ref;
                  }}
                />
              </Panel>
            </Collapse>
          ) : null}
          <FooterToolbar style={{ width: '100%' }}>
            <Button onClick={this.cancel} style={{ marginRight: 10 }}>
              取消
            </Button>
            <Button type="primary" onClick={this.sumSubmit}>
              提交
            </Button>
          </FooterToolbar>
        </Spin>
      </PageHeaderWrapper>
    );
  }
}

export default BasicForm;
